# encoding: utf-8
from .models import Role, RoleMenu
from app.extensions import log, db
from flask import request
from flask_restplus import Resource, fields
from app.extensions.api import Namespace, abort, http_exceptions
from . import parameters, schemas
from app.modules.common.utils import DbCommit, checkToken
from app.modules.common.schemas import BaseSchema

api = Namespace('role', description = "The interface for role operation")  # pylint: disable=invalid-name


@api.route('/')
class RoleClass(Resource):
    @api.parameters(parameters.RoleBaseParameters())
    @api.response(schemas.RoleSchema(many = False))
    @checkToken
    def get(self, args):
        """
        query role list or role info by role_id
        :param args:
        :return:
        """
        _role_id = args['role_id']
        log.info("============== start query role . _role_id is %s ==============" % _role_id)
        if _role_id is None:
            _roles = Role.query.all()
        else:
            _roles = Role.query.filter_by(role_id = _role_id).all()
        return {'success': True, 'msg': '', 'data': _roles}


@api.route('/add')
class addRole(Resource):
    @api.parameters(parameters.RoleAddParameters())
    @api.response(schemas.RoleAddSchema(many = False))
    @checkToken
    def get(self, args):
        """
        add a new role
        :param args:
        :return:
        """
        log.info("============== start add role ==============")
        _role_name = args['role_name']
        _desc = args['desc']
        log.info("============== _role_name is %s ==============" % _role_name)
        log.info("============== _desc is %s ==============" % _desc)
        _role = Role.query.filter_by(role_name = _role_name).all()
        if len(_role) != 0:
            _msg = "add role error . %s is exist" % _role_name
            log.error("============== %s ==============" % _msg)
            return {'success': False, 'msg': _msg}
        else:
            _role = Role(_role_name, _desc)
            db.session.add(_role)
            db.session.flush()
            _rtn = DbCommit()
            if _rtn['success']:
                return {'success': True, 'msg': 'add role %s success' % _role_name, 'data': _role.to_dict()}
            else:
                return _rtn


@api.route('/update')
class addRole(Resource):
    @api.parameters(parameters.RoleUpdateParameters())
    @api.response(BaseSchema(many = False))
    @checkToken
    def get(self, args):
        """
        update role info
        :param args:
        :return:
        """
        log.info("============== start update role ==============")
        _role_id = args['role_id']
        _desc = args['desc']
        log.info("============== _role_id is %s ==============" % _role_id)
        log.info("============== _desc is %s ==============" % _desc)

        if _role_id is None:
            _msg = "update role info , role_id is none"
            log.error("============== %s ==============" % _msg)
            return {'success': False, 'msg': _msg}
        else:
            _role = Role.query.filter_by(role_id = _role_id).first()
            if _role is None:
                _msg = "this role_id %s is not exist" % _role_id
                log.error("============== %s ==============" % _msg)
                return {'success': False, 'msg': _msg}
            else:
                _role.desc = _desc
                return DbCommit()


@api.route('/menu_power')
class addRole(Resource):
    @api.parameters(parameters.UpdateMenuPowerParameters())
    @api.response(BaseSchema(many = False))
    @checkToken
    def get(self, args):
        """
        update role pwoer for menu
        :param args:
        :return:
        """
        log.info("============== start update role pwoer for menu ==============")
        _role_id = args['role_id']
        log.info("============== _role_id is %s ==============" % _role_id)
        _role = Role.query.filter_by(role_id = _role_id).first()
        if _role is None:
            _msg = "this role_id %s is not exist" % _role_id
            log.error("============== %s ==============" % _msg)
            return {'success': False, 'msg': _msg}

        _menu_list = eval(args['menu_list'])
        if type(_menu_list) is not list:
            _msg = "this menu_list %s is not list" % _menu_list
            log.error("============== %s ==============" % _msg)
            return {'success': False, 'msg': _msg}

        _menus = RoleMenu.query.filter_by(role_id = _role_id).all()
        if len(_menus) != 0:
            for _menu in _menus:
                db.session.delete(_menu)
            db.session.commit()

        if _menu_list is not None:
            for _menu_id in _menu_list:
                _role_menu = RoleMenu(_role_id, _menu_id)
                log.info("============== update role pwoer [ _role_id is %s ,_menu_id is %s ] ==============" % (
                    _role_id, _menu_id))
                db.session.add(_role_menu)
            return DbCommit()
        else:
            _msg = "this menu_list is none"
            log.error("============== %s ==============" % _msg)
            return {'success': True, 'msg': _msg}
